package com.face.server.service;

import com.face.RespMsg;
import com.face.server.dao.DormAdminDao;
import com.face.server.dao.JoinedDAO;
import com.face.server.entity.*;
import com.face.server.repository.CameraRepository;
import com.face.server.repository.AdminRepository;
import com.face.server.repository.DormitoryBuildRepository;
import com.face.server.vo.AffectDate;
import com.opencsv.CSVReader;
import com.util.DateUtils;
import com.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CSVService {

    @Autowired
    DormitoryBuildRepository dormitoryBuildRepository;

    @Autowired
    AdminRepository adminRepository;

    @Autowired
    CameraRepository cameraRepository;

    @Autowired
    DormAdminDao dormAdminDao;

    @Autowired
    JoinedDAO joinedDAO;

    @Autowired
    AffectDateService affectDateService;

    public RespMsg parse(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("csv")) {
            return RespMsg.error("当前只支持csv文件");
        }
        try (
                CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(file.getInputStream())));
        ) {
            String[] line;
            int index = 0;
            while ((line = reader.readNext()) != null) {
                int lineNum = line.length;
                index++;
                if (lineNum != 3) {
                    return RespMsg.error(index + "行出现问题，请检查");
                }
                DormitoryBuild build = new DormitoryBuild();
                try {
                    build.setBuildingNum(Integer.parseInt(line[0]));
                    build.setFloorNum(Integer.parseInt(line[1]));
                    build.setRoomPerFloor(Integer.parseInt(line[2]));
                    dormitoryBuildRepository.save(build);
                } catch (Exception e) {
                    return RespMsg.error("对不起， 第" + index + "条记录， " + build + "数据异常，或者数据重复");
                }
            }
            return RespMsg.build("解析成功，共" + index + "条数据");
        }
    }

    public RespMsg parseAdmin(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("csv")) {
            return RespMsg.error("当前只支持csv文件");
        }
        try (
                CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(file.getInputStream())));
        ) {
            String[] line;
            int index = 0;
            while ((line = reader.readNext()) != null) {
                int lineNum = line.length;
                index++;
                if (lineNum != 4) {
                    return RespMsg.error(index + "行出现问题，请检查");
                }
                Admin admin = new Admin();
                try {
                    admin.setName(line[0]);
                    admin.setSex(Boolean.parseBoolean(line[1]));
                    admin.setPhone(line[2]);
                    admin.setIdentity(line[3]);
                    admin.getAuth().setUsername(admin.getPhone());
                    admin.getAuth().setPassword(StringUtils.substringLast(admin.getIdentity(), 6));
                    adminRepository.save(admin);
                } catch (Exception e) {
                    return RespMsg.error("对不起， 第" + index + "条记录， " + admin + "数据异常，或者数据重复");
                }
            }

            return RespMsg.build("解析成功，共" + index + "条数据");
        }
    }

    public RespMsg parseCamera(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("csv")) {
            return RespMsg.error("当前只支持csv文件");
        }
        try (
                CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(file.getInputStream())));
        ) {
            String[] line;
            int index = 0;
            while ((line = reader.readNext()) != null) {
                int lineNum = line.length;
                index++;
                if (lineNum != 3) {
                    return RespMsg.error(index + "行出现问题，请检查");
                }
                Camera camera = new Camera();
                try {
                    camera.setDormitoryBuildNum(Integer.parseInt(line[0]));
                    camera.setMac(line[1]);
                    camera.setClosed(Boolean.parseBoolean(line[2]));
                    cameraRepository.save(camera);
                } catch (NumberFormatException e) {
                    return RespMsg.error("对不起， 第" + index + "条记录， " + camera + "数据异常，或者数据重复");
                }
            }
            return RespMsg.build("解析成功，共" + index + "条数据");
        }
    }

    public RespMsg parseDormAdmin(MultipartFile file) throws IOException{
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("csv")) {
            return RespMsg.error("当前只支持csv文件");
        }
        try (
                CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(file.getInputStream())));
        ) {
            String[] line;
            int index = 0;
            while ((line = reader.readNext()) != null) {
                int lineNum = line.length;
                index++;
                if (lineNum != 6) {
                    return RespMsg.error(index + "行出现问题，请检查");
                }
                DormitoryAdmin dormitoryAdmin=new DormitoryAdmin();
                try {
                    dormitoryAdmin.setName(line[0]);
                    dormitoryAdmin.setPhone(line[1]);
                    dormitoryAdmin.setSex(Boolean.parseBoolean(line[2]));
                    dormitoryAdmin.setJobName(line[3]);
                    dormitoryAdmin.setIdentity(line[4]);
                    dormitoryAdmin.setDormitoryBuildNum(Integer.parseInt(line[5]));
                    DormitoryBuild dormitoryBuild=dormitoryBuildRepository.findByBuildingNum(dormitoryAdmin.getDormitoryBuildNum());
                    dormitoryAdmin.setType(2);
                    dormitoryAdmin.setDormitoryBuild(dormitoryBuild);
                    dormAdminDao.create(dormitoryAdmin);
                } catch (NumberFormatException e) {
                    return RespMsg.error("对不起， 第" + index + "条记录， " + dormitoryAdmin + "数据异常，或者数据重复");
                }
            }
            return RespMsg.build("解析成功，共" + index + "条数据");
        }
    }

    public RespMsg parseStudent(MultipartFile file) throws IOException{
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("csv")) {
            return RespMsg.error("当前只支持csv文件");
        }
        try (
                CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(file.getInputStream())));
        ) {
            String[] line;
            int index = 0;
            while ((line = reader.readNext()) != null) {
                int lineNum = line.length;
                index++;
                if (lineNum != 8) {
                    return RespMsg.error(index + "行出现问题，请检查");
                }
                Student student=new Student();
                try {
                    student.setType(0);
                    student.setPoint(0);
                    student.setName(line[0]);
                    student.setSex(Boolean.parseBoolean(line[1]));
                    student.setStudentNumber(Integer.parseInt(line[2]));
                    student.setClassName(line[3]);
                    student.setIdentity(line[4]);
                    student.setPhone(line[5]);
                    student.setDormitoryBuildNum(Integer.parseInt(line[6]));
                    student.setDormitoryNum(Integer.parseInt(line[7]));
                    student.getAuth().setUsername(student.getPhone());
                    student.getAuth().setPassword(StringUtils.substringLast(student.getIdentity(), 6));
                    DormitoryBuild dormitoryBuild=dormitoryBuildRepository.findByBuildingNum(student.getDormitoryBuildNum());
                    student.setDormitoryBuild(dormitoryBuild);
                    joinedDAO.createStudent(student);
                } catch (NumberFormatException e) {
                    return RespMsg.error("对不起， 第" + index + "条记录， " + student + "数据异常，或者数据重复");
                }
            }
            return RespMsg.build("解析成功，共" + index + "条数据");
        }
    }

    public RespMsg saveAffectDate(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith("csv")) {
            return RespMsg.error("当前只支持csv文件");
        }
        try (
                CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(file.getInputStream())));
        ) {
            String[] line;
            int index = 0;
            while ((line = reader.readNext()) != null) {
                int lineNum = line.length;
                index++;
                if (lineNum != 3) {
                    return RespMsg.error(index + "行出现问题，请检查");
                }
                AffectDate affectDate = new AffectDate();
                try {
                    affectDate.setClassName(line[0]);
                    affectDate.setClassBegin(DateUtils.parse(line[1]));
                    affectDate.setClassEnd(DateUtils.parse(line[2]));
                    affectDateService.save(affectDate);
                } catch (NumberFormatException e) {
                    return RespMsg.error("对不起， 第" + index + "条记录， " + affectDate + "数据异常，或者数据重复");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            return RespMsg.build("解析成功，共" + index + "条数据");
        }
    }
}
